import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';

class ReportsStatisticsScreen extends StatefulWidget {
  const ReportsStatisticsScreen({Key? key}) : super(key: key);

  @override
  State<ReportsStatisticsScreen> createState() => _ReportsStatisticsScreenState();
}

class _ReportsStatisticsScreenState extends State<ReportsStatisticsScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _selectedTabIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _selectedTabIndex = _tabController.index;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        appBar: AppBar(
          title: const Text(
            'دوكلات ۋە ستاتىستىكا',
            style: TextStyle(
              color: Color(0xFFFF8C00),
              fontWeight: FontWeight.bold,
              fontSize: 20,
              shadows: [
                Shadow(
                  offset: Offset(1.0, 1.0),
                  blurRadius: 3.0,
                  color: Color.fromARGB(150, 0, 0, 0),
                ),
              ],
            ),
          ),
          backgroundColor: const Color(0xFF3F5491),
          centerTitle: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () => Navigator.of(context).pop(),
          ),
          bottom: TabBar(
            controller: _tabController,
            indicatorColor: Colors.white,
            indicatorWeight: 3,
            labelColor: Colors.red,
            unselectedLabelColor: Colors.white,
            labelStyle: const TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              shadows: [
                Shadow(
                  offset: Offset(1.0, 1.0),
                  blurRadius: 3.0,
                  color: Color.fromARGB(255, 0, 0, 0),
                ),
              ],
            ),
            tabs: const [
              Tab(text: 'سېتىش دوكلاتى'),
              Tab(text: 'كىرىم-چىقىم دوكلاتى'),
              Tab(text: 'ئامبار دوكلاتى'),
            ],
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: [
            _buildSalesReportTab(),
            _buildFinanceReportTab(),
            _buildInventoryReportTab(),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          backgroundColor: const Color(0xFF3F5491),
          onPressed: () {
            _showExportDialog(context);
          },
          tooltip: 'دوكلاتنى چىقىرىش',
          child: const Icon(Icons.download),
        ),
      ),
    );
  }

  Widget _buildSalesReportTab() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.grey.shade100,
            Colors.white,
          ],
        ),
      ),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDateRangeSelector(),
            const SizedBox(height: 24),
            
            // سېتىش ئومۇمىي دوكلات كارتىسى
            _buildSummaryCard(
              title: 'ئومۇمىي سېتىش دوكلاتى',
              data: [
                {'label': 'بۈگۈن سېتىلغان سانى', 'value': '45 دانە'},
                {'label': 'ھەپتىلىك سېتىلغان سانى', 'value': '278 دانە'},
                {'label': 'ئايلىق سېتىلغان سانى', 'value': '1,205 دانە'},
                {'label': 'بۈگۈنكى سېتىش سوممىسى', 'value': '¥4,350'},
                {'label': 'ھەپتىلىك سېتىش سوممىسى', 'value': '¥25,740'},
                {'label': 'ئايلىق سېتىش سوممىسى', 'value': '¥118,650'},
              ],
            ),
            const SizedBox(height: 24),
            
            // سېتىش گرافىكى ۋە ئەڭ كۆپ سېتىلغان مەھسۇلاتلار
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // سېتىش گرافىكى
                Expanded(
                  child: _buildChartCard(
                    title: 'ئايلىق سېتىش گرافىكى',
                    height: 300,
                    chart: LineChart(
                      LineChartData(
                        gridData: FlGridData(show: true, drawVerticalLine: true),
                        titlesData: FlTitlesData(
                          bottomTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              reservedSize: 30,
                              getTitlesWidget: (value, meta) {
                                const labels = ['1', '2', '3', '4'];
                                int index = value.toInt();
                                if (index >= 0 && index < labels.length) {
                                  return Text(
                                    labels[index],
                                    style: const TextStyle(
                                      fontSize: 14,
                                      color: Colors.black54,
                                    ),
                                  );
                                }
                                return const SizedBox();
                              },
                            ),
                          ),
                          leftTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              reservedSize: 40,
                              getTitlesWidget: (value, meta) {
                                return Text('¥${value.toInt()}K');
                              },
                            ),
                          ),
                          topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                          rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                        ),
                        borderData: FlBorderData(show: true),
                        lineBarsData: [
                          LineChartBarData(
                            spots: const [
                              FlSpot(0, 20),
                              FlSpot(1, 35),
                              FlSpot(2, 28),
                              FlSpot(3, 32),
                            ],
                            isCurved: true,
                            color: const Color(0xFF4A6FE5),
                            barWidth: 3,
                            dotData: FlDotData(show: true),
                            belowBarData: BarAreaData(
                              show: true,
                              color: const Color(0xFF4A6FE5).withOpacity(0.15),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                
                const SizedBox(width: 16), // ئارىلىق
                
                // ئەڭ كۆپ سېتىلغان مەھسۇلاتلار
                Expanded(
                  child: _buildDataTableCard(
                    title: 'ئەڭ كۆپ سېتىلغان مەھسۇلاتلار',
                    columns: const ['مەھسۇلات ئىسمى', 'سېتىلغان سانى', 'سېتىش سوممىسى'],
                    rows: [
                      ['ئالما iPhone 14 Pro', '36 دانە', '¥43,200'],
                      ['تېلېۋىزور Xiaomi 65\"', '24 دانە', '¥31,200'],
                      ['Macbook Pro M1', '18 دانە', '¥27,000'],
                      ['كىر يۇيۇش ماشىنىسى Haier', '15 دانە', '¥9,750'],
                      ['سۇغۇتقۇچ SAMSUNG', '12 دانە', '¥9,600'],
                    ],
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }

  Widget _buildFinanceReportTab() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.grey.shade100,
            Colors.white,
          ],
        ),
      ),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDateRangeSelector(),
            const SizedBox(height: 24),
            
            // كىرىم-چىقىم ئومۇمىي دوكلات كارتىسى
            _buildSummaryCard(
              title: 'ئومۇمىي كىرىم-چىقىم دوكلاتى',
              data: [
                {'label': 'ئومۇمىي كىرىم', 'value': '¥215,500'},
                {'label': 'ئومۇمىي چىقىم', 'value': '¥142,800'},
                {'label': 'سۈپ پايدا', 'value': '¥72,700'},
                {'label': 'كىرىم-چىقىم نىسبىتى', 'value': '1.51'},
              ],
            ),
            const SizedBox(height: 24),
            
            // كىرىم-چىقىم دىئاگرام ۋە چىقىم تۈرلىرى بويىچە دوكلات
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // كىرىم-چىقىم دىئاگرام
                Expanded(
                  child: _buildChartCard(
                    title: 'كىرىم-چىقىم دىئاگراممىسى',
                    height: 300,
                    chart: PieChart(
                      PieChartData(
                        sectionsSpace: 2,
                        centerSpaceRadius: 70,
                        sections: [
                          PieChartSectionData(
                            value: 60,
                            title: 'كىرىم',
                            color: const Color(0xFF2ECC71),
                            radius: 100,
                            titleStyle: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                          PieChartSectionData(
                            value: 40,
                            title: 'چىقىم',
                            color: const Color(0xFFE74C3C),
                            radius: 100,
                            titleStyle: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                
                const SizedBox(width: 16), // ئارىلىق
                
                // چىقىم تۈرلىرى بويىچە دوكلات
                Expanded(
                  child: _buildDataTableCard(
                    title: 'چىقىم تۈرلىرى بويىچە دوكلات',
                    columns: const ['چىقىم تۈرى', 'سوممىسى', 'پىرسەنتى'],
                    rows: [
                      ['تاۋار سېتىۋېلىش', '¥98,500', '69%'],
                      ['ئىجارە', '¥18,000', '12.5%'],
                      ['مائاش', '¥15,500', '10.9%'],
                      ['ئېلېكتىر ۋە گاز', '¥5,200', '3.6%'],
                      ['باشقا', '¥5,600', '4%'],
                    ],
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }

  Widget _buildInventoryReportTab() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.grey.shade100,
            Colors.white,
          ],
        ),
      ),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDateRangeSelector(),
            const SizedBox(height: 24),
            
            // ئامبار ئومۇمىي دوكلات كارتىسى
            _buildSummaryCard(
              title: 'ئومۇمىي ئامبار دوكلاتى',
              data: [
                {'label': 'ئامباردىكى مەھسۇلات تۈرى', 'value': '128 تۈر'},
                {'label': 'ئامباردىكى مەھسۇلات سانى', 'value': '2,556 دانە'},
                {'label': 'ئامباردىكى مەھسۇلات قىممىتى', 'value': '¥354,200'},
                {'label': 'ئاز قالغان مەھسۇلاتلار', 'value': '14 تۈر'},
              ],
            ),
            const SizedBox(height: 24),
            
            // ئامبار دىئاگرام ۋە ئاز قالغان مەھسۇلاتلار
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // ئامبار دىئاگرام
                Expanded(
                  child: _buildChartCard(
                    title: 'كاتېگورىيە بويىچە ئامبار دىئاگراممىسى',
                    height: 300,
                    chart: BarChart(
                      BarChartData(
                        alignment: BarChartAlignment.spaceAround,
                        maxY: 100,
                        barTouchData: BarTouchData(
                          enabled: true,
                          touchTooltipData: BarTouchTooltipData(
                            getTooltipItem: (group, groupIndex, rod, rodIndex) {
                              String category = '';
                              switch (group.x) {
                                case 0:
                                  category = 'ئېلېكترونىكا';
                                  break;
                                case 1:
                                  category = 'كىيىم-كېچەك';
                                  break;
                                case 2:
                                  category = 'ئۆي جابدۇقلىرى';
                                  break;
                                case 3:
                                  category = 'يېمەك-ئىچمەك';
                                  break;
                                case 4:
                                  category = 'باشقا';
                                  break;
                                default:
                                  category = '';
                              }
                              return BarTooltipItem(
                                category + '\n' + '\$${rod.toY.round()}K',
                                const TextStyle(color: Colors.white),
                              );
                            },
                          ),
                        ),
                        titlesData: FlTitlesData(
                          show: true,
                          bottomTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              getTitlesWidget: (value, meta) {
                                String text = '';
                                switch (value.toInt()) {
                                  case 0:
                                    text = 'ئېلېكترونىكا';
                                    break;
                                  case 1:
                                    text = 'كىيىم-كېچەك';
                                    break;
                                  case 2:
                                    text = 'ئۆي جابدۇقلىرى';
                                    break;
                                  case 3:
                                    text = 'يېمەك-ئىچمەك';
                                    break;
                                  case 4:
                                    text = 'باشقا';
                                    break;
                                  default:
                                    text = '';
                                }
                                return Text(
                                  text, 
                                  style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black54,
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                        gridData: FlGridData(show: false),
                        borderData: FlBorderData(show: false),
                        barGroups: [
                          BarChartGroupData(
                            x: 0,
                            barRods: [
                              BarChartRodData(
                                toY: 80,
                                color: const Color(0xFF3498DB),
                                width: 22,
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(6),
                                  topRight: Radius.circular(6),
                                ),
                              ),
                            ],
                          ),
                          BarChartGroupData(
                            x: 1,
                            barRods: [
                              BarChartRodData(
                                toY: 55,
                                color: const Color(0xFF3498DB),
                                width: 22,
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(6),
                                  topRight: Radius.circular(6),
                                ),
                              ),
                            ],
                          ),
                          BarChartGroupData(
                            x: 2,
                            barRods: [
                              BarChartRodData(
                                toY: 68,
                                color: const Color(0xFF3498DB),
                                width: 22,
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(6),
                                  topRight: Radius.circular(6),
                                ),
                              ),
                            ],
                          ),
                          BarChartGroupData(
                            x: 3,
                            barRods: [
                              BarChartRodData(
                                toY: 40,
                                color: const Color(0xFF3498DB),
                                width: 22,
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(6),
                                  topRight: Radius.circular(6),
                                ),
                              ),
                            ],
                          ),
                          BarChartGroupData(
                            x: 4,
                            barRods: [
                              BarChartRodData(
                                toY: 23,
                                color: const Color(0xFF3498DB),
                                width: 22,
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(6),
                                  topRight: Radius.circular(6),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                
                const SizedBox(width: 16), // ئارىلىق
                
                // ئاز قالغان مەھسۇلاتلار
                Expanded(
                  child: _buildDataTableCard(
                    title: 'ئاز قالغان مەھسۇلاتلار',
                    columns: const ['مەھسۇلات ئىسمى', 'قالغان سانى', 'مىنىمۇم سانى'],
                    rows: [
                      ['ئالما iPhone 14 Pro', '5 دانە', '10 دانە'],
                      ['قول تېلېفون Xiaomi 13', '8 دانە', '15 دانە'],
                      ['Macbook Pro M1', '3 دانە', '5 دانە'],
                      ['تېلېۋىزور Sony 55\"', '4 دانە', '8 دانە'],
                      ['ئۆي كوندىتسىيونېرى Gree', '6 دانە', '10 دانە'],
                    ],
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }

  Widget _buildDateRangeSelector() {
    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'ۋاقىت تاللاش',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () {},
                    icon: const Icon(Icons.calendar_today),
                    label: const Text('2023-10-01'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      side: BorderSide(color: Colors.grey.shade300),
                      foregroundColor: const Color(0xFF2980B9),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () {},
                    icon: const Icon(Icons.calendar_today),
                    label: const Text('2023-10-31'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      side: BorderSide(color: Colors.grey.shade300),
                      foregroundColor: const Color(0xFF2980B9),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                SizedBox(
                  height: 46,
                  child: ElevatedButton.icon(
                    onPressed: () {},
                    icon: const Icon(Icons.search),
                    label: const Text('ئىزدەش'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF2980B9),
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  _buildDateFilter('بۈگۈن', true),
                  _buildDateFilter('بۇ ھەپتە', false),
                  _buildDateFilter('بۇ ئاي', false),
                  _buildDateFilter('ئۆتكەن ئاي', false),
                  _buildDateFilter('بۇ يىل', false),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDateFilter(String label, bool isSelected) {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: FilterChip(
        label: Text(label),
        selected: isSelected,
        onSelected: (bool selected) {},
        backgroundColor: Colors.grey.shade200,
        selectedColor: const Color(0xFFFF8C00).withOpacity(0.2),
        checkmarkColor: const Color(0xFFFF8C00),
      ),
    );
  }

  Widget _buildSummaryCard({
    required String title,
    required List<Map<String, String>> data,
  }) {
    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: 2.5,
                crossAxisSpacing: 8,
                mainAxisSpacing: 16,
              ),
              itemCount: data.length,
              itemBuilder: (context, index) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      data[index]['label']!,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey.shade600,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      data[index]['value']!,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildChartCard({
    required String title,
    required double height,
    required Widget chart,
  }) {
    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.more_vert),
                  onPressed: () {},
                ),
              ],
            ),
            SizedBox(
              height: height,
              child: chart,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDataTableCard({
    required String title,
    required List<String> columns,
    required List<List<String>> rows,
  }) {
    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: DataTable(
                columnSpacing: 24,
                headingTextStyle: const TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF3F5491),
                ),
                dataTextStyle: const TextStyle(
                  color: Colors.black87,
                ),
                columns: columns
                    .map((column) => DataColumn(
                          label: Text(column),
                        ))
                    .toList(),
                rows: rows
                    .map(
                      (row) => DataRow(
                        cells: row
                            .map((cell) => DataCell(Text(cell)))
                            .toList(),
                      ),
                    )
                    .toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showExportDialog(BuildContext context) {
    final List<String> exportOptions = [
      'PDF شەكلىدە چۈشۈرۈش',
      'Excel شەكلىدە چۈشۈرۈش',
      'بېسىش',
      'ئېلخەت قىلىش',
    ];

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('دوكلاتنى چىقىرىش'),
          content: SizedBox(
            width: double.maxFinite,
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: exportOptions.length,
              itemBuilder: (context, index) {
                return ListTile(
                  leading: Icon(
                    index == 0 ? Icons.picture_as_pdf :
                    index == 1 ? Icons.table_chart :
                    index == 2 ? Icons.print :
                    Icons.email,
                    color: const Color(0xFFFF8C00),
                  ),
                  title: Text(exportOptions[index]),
                  onTap: () {
                    Navigator.pop(context);
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('${exportOptions[index]} تاللاندى'),
                        backgroundColor: const Color(0xFFFF8C00),
                      ),
                    );
                  },
                );
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('ئىناۋەتسىز'),
            ),
          ],
        );
      },
    );
  }
} 